{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving Molecules as Images"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a quick tutorial on how to save rdkit molecules as image files.\n",
    "\n",
    "@TAGS: #basics #output #fileoperations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aS364UWTE4D-"
   },
   "source": [
    "## To save an rdkit mol as an SVG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "X3fS7HJeEisX"
   },
   "outputs": [],
   "source": [
    "from rdkit.Chem.Draw import rdMolDraw2D\n",
    "from rdkit.Chem import MolFromSmiles\n",
    "canvas_width_pixels = 300\n",
    "canvas_height_pixels  = 300\n",
    "input_smiles = 'CCCC'\n",
    "mol = MolFromSmiles(input_smiles)\n",
    "mol = rdMolDraw2D.PrepareMolForDrawing(mol)\n",
    "drawer = rdMolDraw2D.MolDraw2DSVG(canvas_width_pixels,canvas_height_pixels)\n",
    "drawer.DrawMolecule(mol)\n",
    "drawer.FinishDrawing()\n",
    "svg = drawer.GetDrawingText()\n",
    "with open('output.svg', 'w') as f:\n",
    "    f.write(svg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Nr4R7_cwFfC2"
   },
   "source": [
    "## To Save a MolsToGridImage as a PNG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "c1NqPO9HFrzJ",
    "outputId": "5209a094-cbca-47f5-a742-50eee7442cd1"
   },
   "outputs": [],
   "source": [
    "from rdkit import Chem\n",
    "from rdkit.Chem import Draw\n",
    "from rdkit.Chem.Draw import IPythonConsole\n",
    "benzene = Chem.MolFromSmiles('C1=CC=CC=C1')\n",
    "butane = Chem.MolFromSmiles('CCCC')\n",
    "propane = Chem.MolFromSmiles('CCC')\n",
    "ethane = Chem.MolFromSmiles('CC')\n",
    "methane = Chem.MolFromSmiles('C')\n",
    "\n",
    "img = Draw.MolsToGridImage([benzene, methane, ethane, propane, butane], returnPNG=True)\n",
    "open('output_mols_to_grid.png', 'wb').write(img.data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "0oof8NknIKsz"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
